<template>
  <div>

    <!--下载进度条-->
    <el-dialog
      title="正在下载，请等待..."
      :visible.sync="fileDown.loadDialogStatus"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="20%"
      :append-to-body='true'
    >
      <div style="text-align: center;">
        <el-progress
          type="circle"
          :percentage="fileDown.percentage"
        ></el-progress>
      </div>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="downClose"
          size="small"
          round
        >取消下载</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import axios from 'axios';
import Vue from 'vue';
import { ACCESS_TOKEN } from '@/store/constant';
export default {
  data() {
    return {
      fileDown: {
        loadDialogStatus: false, //弹出框控制的状态
        percentage: 0, //进度条的百分比
        source: {}, //取消下载时的资源对象
      },
    };
  },
  methods: {
    /**
     * 调用下载方法
     */
    downFile(url, params) {
      this.fileDown.loadDialogStatus = true;
      this.fileDown.percentage = 0;
      const instance = this.initInstance();
      let baseUrl = window.global_value.VUE_APP_API_URL || '/';
      instance({
        method: 'get',
        withCredentials: true,
        url: baseUrl + url,
        params: params,
        responseType: 'blob',
      })
        .then((res) => {
          this.fileDown.loadDialogStatus = false;
          console.info(res);
          const content = res.data;
          if (content.size == 0) {
            this.loadClose();
            this.$alert('下载失败');
            return;
          }
          const blob = content;
          // 获取文件名fileName
          let fileName = res.headers['content-disposition'].split('=');
          fileName = fileName[fileName.length - 1];
          fileName = fileName.replace(/"/g, '');
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a');
            elink.download = fileName;
            elink.style.display = 'none';
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            setTimeout(function () {
              URL.revokeObjectURL(elink.href); // 释放URL 对象
              document.body.removeChild(elink);
            }, 100);
          } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName);
          }
        })
        .catch((error) => {
          this.fileDown.loadDialogStatus = false;
          console.info(error);
        });
    },
    initInstance() {
      var _this = this;
      //取消时的资源标记
      this.fileDown.source = axios.CancelToken.source();
      const instance = axios.create({
        //axios 这个对象要提前导入 或者替换为你们全局定义的
        onDownloadProgress: function (ProgressEvent) {
          const load = ProgressEvent.loaded;
          const total = ProgressEvent.total;
          const progress = (load / total) * 100;
          console.log('ProgressEvent', ProgressEvent);
          //一开始已经在计算了 这里要超过先前的计算才能继续往下
          if (progress > _this.fileDown.percentage) {
            _this.fileDown.percentage = Math.floor(progress);
          }
          if (progress == 100) {
            //下载完成
            _this.fileDown.loadDialogStatus = false;
          }
        },
        cancelToken: this.fileDown.source.token, //声明一个取消请求token
      });
      //添加token
      instance.interceptors.request.use(
        (config) => {
          const token = Vue.ls.get(ACCESS_TOKEN);
          if (token) {
            config.headers[ACCESS_TOKEN] = token; // 让每个请求携带自定义 token 请根据实际情况自行修改
          }

          return config;
        },
        (error) => {
          return Promise.reject(error);
        }
      );
      return instance;
    },
    downClose() {
      //中断下载
      this.$confirm('点击关闭后将中断下载，是否确定关闭？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          //中断下载回调
          this.fileDown.source.cancel('log==客户手动取消下载');
        })
        .catch(() => {
          //取消--什么都不做
        });
    },
  },
};
</script>

<style lang="sass" scoped>
</style>